package com.doudou.oauth.token;

import com.doudou.oauth.entity.AppTokenUtil;
import com.doudou.oauth.service.AppUserRoleService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 傻男人
 * @Date: 2020/6/10 10:05
 * @Version: 1.0
 * @Description:
 */
public class AppCodeTokenGranter extends AbstractTokenGranter {


    UserDetailsService userDetailsService;

    private final AppUserRoleService appUserRoleService;

    public AppCodeTokenGranter(AuthorizationServerTokenServices tokenServices,
                               ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory,
                               UserDetailsService userDetailsService,
                               AppUserRoleService appUserRoleService) {
        super(tokenServices, clientDetailsService, requestFactory, AppTokenUtil.APP_CODE);
        this.userDetailsService = userDetailsService;
        this.appUserRoleService = appUserRoleService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        String appCode = parameters.get(AppTokenUtil.APP_CODE);
        if(appCode ==null){
            throw new InvalidGrantException("参数APP_CODE不存在");
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

        Map<String, Object> map = this.appUserRoleService.loadUserByAppCode(appCode);

        Authentication userAuth = userRoleAuth(storedOAuth2Request, (UserDetails)map.get("user"));

        if(userAuth ==null){
            throw new InvalidGrantException("账户信息不存在");
        }

        Map<String, Serializable> extensions = storedOAuth2Request.getExtensions();

        extensions.put("tenantId", (String)map.get("tenantId"));
        extensions.put("schoolId", (String)map.get("schoolId"));


        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }


    private Authentication userRoleAuth(OAuth2Request oAuth2Request, UserDetails userDetails){



        if(userDetails ==null){
            throw new InvalidGrantException("账户信息不存在");
        }

        Collection<? extends GrantedAuthority> roles = loadRole(oAuth2Request.getClientId(),userDetails.getUsername());
        User user =new User(userDetails.getUsername(),
                userDetails.getPassword(),
                roles);

        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(user,userDetails.getPassword(),roles);

        return  auth;
    }

    Collection<? extends GrantedAuthority> loadRole(String appId,String userName){
        return  appUserRoleService.loadRole(appId,userName);
    }
}

